package com.shwread.android.qysw.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.CommonWebView;
import com.shwread.android.ui.customview.GoodsPropPopView;
import com.shwread.android.ui.customview.GoodsPropViewListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.WebGoback;
import com.shwread.android.ui.dialog.CommonLoadingDialog;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.GoodsBaseInfo;
import logic.bean.GoodsSkuMapInfo;
import logic.bean.ShoppingCart;
import logic.constants.AppConfig;
import logic.constants.DefaultConsts;
import logic.dao.ShoppingCartDao;
import logic.util.Utils;


/**
 * @author xuzhijun
 * @date 2015年3月25日 上午10:05:46
 *       商品基本信息页面
 */
public class NewGoodsMainActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private final int           STATE_ADD   = 2;
	private final int           STATE_BUY   = 3;
	
	private int                 loadState   = 0;
	private final int           loadSuccess = 1;
	private final int           loadfail    = 2;
	
	private Context             mContext;
	private TextView            tvTitle;
	private Button              btnBack;
	
	private final int           TAB_BASE    = 0;
	private final int           TAB_DETAIL  = 1;
	//	private WebView               webView;
	private RelativeLayout      ralyWebView;
	//	private String                mUrl         = "http://www.baidu.com";
	
	private ImageView           gotoShoppingCartActivityImg;
	private Button              btnAddShoppingCart;         //加入购物车
	private Button              btnBuy;                     //立刻购买
	private Button              btnPopupConfirm;            //popupWindow确认
	private GoodsBaseInfo       goodsInfo;
	
	private QYViewPager         viewPager;
	private List<CommonWebView> viewList;
	
	private TextView            tvGoodsBase, tvGoodsDetail;
	
	private GoodsPropPopView    popupWindow;
	private View                popupView;
	private int                 currentPage = 0;
	/** 应用是否退出 */
	private boolean             isAppExit   = false;
	
	private ShoppingCartDao     shoppingCartDao;
	
	private String              goodsBaseUrl;
	private String              GoodsDetailUrl;
	private long                goodsId;
	private String              activityPrice;
	//	private long = 
	
	private CommonWebView       commonBaseWebView;          //商品基本信息页面
	private CommonWebView       commonDetailWebView;        //商品详情页面
	                                                         
	private CommonLoadingDialog loadingDialog;
	private int                 popWhich    = 0;
	
	private int                 freeMoney   = 0;
	private long                activityId  = 0;
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods_main_new);
		mContext = this;
		initView();
		initData();
		setListener();
		
		if (savedInstanceState != null)
		{
			commonBaseWebView.webView.restoreState(savedInstanceState);
			commonDetailWebView.webView.restoreState(savedInstanceState);
		}
	}
	
	private void initView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setVisibility(View.GONE);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		
		tvGoodsBase = (TextView) findViewById(R.id.goods_main_base_tab);
		tvGoodsDetail = (TextView) findViewById(R.id.goods_main_detail_tab);
		
		ralyWebView = (RelativeLayout) findViewById(R.id.goods_main_ray);
		btnAddShoppingCart = (Button) findViewById(R.id.goods_main_bottom_add_btn);
		btnBuy = (Button) findViewById(R.id.goods_main_bottom_buy_btn);
		gotoShoppingCartActivityImg = (ImageView) findViewById(R.id.goods_main_bottom_shoppingcart_img);
		viewPager = (QYViewPager) findViewById(R.id.goods_main_vp);
		
		popupView = LayoutInflater.from(mContext).inflate(R.layout.goods_main_popup, null);
		btnPopupConfirm = (Button) popupView.findViewById(R.id.goods_main_popup_confirm);
	}
	
	private void initData() {
		loadingDialog = new CommonLoadingDialog(mContext);
		goodsBaseUrl = getIntent().getExtras().getString(DefaultConsts.GOODS_BASE_URL_TO_WAP);
		GoodsDetailUrl = getIntent().getExtras().getString(DefaultConsts.GOODS_DETAIL_URL_TO_WAP);
		goodsId = getIntent().getExtras().getLong(DefaultConsts.GOODS_ID_TO_WAP);
		freeMoney = getIntent().getExtras().getInt(DefaultConsts.GOODS_FREE_MONEY_TO_WAP);
		activityId = getIntent().getExtras().getLong(DefaultConsts.GOODS_ACTIVITY_PRICE_ID);
		int price = getIntent().getExtras().getInt(DefaultConsts.GOODS_ACTIVITY_PRICE_TO_WAP);
		if (price == 0)
		{
			activityPrice = "0";
		}
		else
		{
			activityPrice = Integer.toString(price);
		}
		goodsBaseUrl = Utils.appendString(goodsBaseUrl, Long.toString(goodsId), String.valueOf(freeMoney));
		//		goodsBaseUrl = Utils.appendString(goodsBaseUrl, Long.toString(goodsId), activityPrice);
		
		//		if (goodsId < 1)
		//		{
		//			goodsId = 3L;
		//		}
		//		if (Utils.isEmpty(goodsUrl))
		//		{
		//			goodsUrl = "https://www.baidu.com";
		//		}
		
		ActionHelp.qryGoodsBase(mContext, goodsId, new GoodsBaseHandler());
		
		commonBaseWebView = new CommonWebView(mContext, goodsBaseUrl, new WebGoback()
		{
			
			@Override
			public void goBack() {
				BaseBusinessActivity.uiHandler.post(new Runnable()
				{
					@Override
					public void run() {
						onBackPressed();
					}
				});
			}
		});
		commonDetailWebView = new CommonWebView(mContext, GoodsDetailUrl, new WebGoback()
		{
			
			@Override
			public void goBack() {
				BaseBusinessActivity.uiHandler.post(new Runnable()
				{
					@Override
					public void run() {
						onBackPressed();
					}
				});
			}
		});
		viewList = new ArrayList<CommonWebView>();
		viewList.add(commonBaseWebView);
		viewList.add(commonDetailWebView);
		viewPager.setAdapter(new ViewPagerWebAdapter());
		setSelect(TAB_BASE);
		viewPager.setSliding(false);
		//		viewPager.setOnPageChangeListener(new OnPageChangeListener()
		//		{
		//			
		//			@Override
		//			public void onPageSelected(int arg0) {
		//				setSelect(arg0);
		//			}
		//			
		//			@Override
		//			public void onPageScrolled(int arg0, float arg1, int arg2) {
		//				
		//			}
		//			
		//			@Override
		//			public void onPageScrollStateChanged(int arg0) {
		//				
		//			}
		//		});
		//		setSelect(TAB_BASE);
	}
	
	private class GoodsBaseHandler
	        extends
	        ObjectHttpResponseHandler<GoodsBaseInfo>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			//			if (statusCode < 1000)
			//			{
			//				Utils.ToastShow(mContext, "网络错误");
			//			}
			//			else
			//			{
			//				Utils.ToastShow(mContext, "请求出错");
			//			}
			loadState = loadfail;
			loadingDialog.dismiss();
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, GoodsBaseInfo object, String responseString) {
			System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
			goodsInfo = object;
			loadState = loadSuccess;
			if (loadingDialog.isShowing())
			{
				popupWindow = new GoodsPropPopView(mContext, goodsInfo);
				switch (popWhich) {
					case STATE_ADD:
						popupWindow.setSkuListener(new ShoppingCartAddListener());
						
						break;
					case STATE_BUY:
						popupWindow.setSkuListener(new BuyNowListener());
						break;
				}
				loadingDialog.dismiss();
				popupWindow.showWindow();
			}
			popWhich = 0;
			
			if (Utils.isEmpty(GoodsDetailUrl))
			{
				commonDetailWebView.setmUrl(goodsInfo.getDetailUrl());
				commonDetailWebView.setWebView();
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<GoodsBaseInfo>()
			{
			}.getType();
		}
		
	}
	
	private void setListener() {
		btnBack.setOnClickListener(this);
		btnBuy.setOnClickListener(this);
		btnAddShoppingCart.setOnClickListener(this);
		gotoShoppingCartActivityImg.setOnClickListener(this);
		tvGoodsBase.setOnClickListener(this);
		tvGoodsDetail.setOnClickListener(this);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		commonBaseWebView.webView.saveState(outState);
		commonDetailWebView.webView.saveState(outState);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				goback();
				break;
			case R.id.goods_main_bottom_add_btn:
				popWhich = STATE_ADD;
				//				popupWindow = new GoodsPropPopView(mContext, goodsInfo);
				//				, new GoodsPropViewListener()
				//				{
				//					@Override
				//					public void OK(GoodsSkuMapInfo goodsSkuMapInfo, String propString, int count, Dialog d) {
				//						
				//					}
				//					
				//				});
				if (goodsInfo != null)
				{
					popupWindow = new GoodsPropPopView(mContext, goodsInfo, freeMoney, activityId);
					popupWindow.setSkuListener(new ShoppingCartAddListener());
					popupWindow.showWindow();
				}
				else
				{
					if (!(loadState == loadfail))
					{
						loadingDialog.show();
					}
				}
				break;
			case R.id.goods_main_bottom_buy_btn:
				popWhich = STATE_BUY;
				//				popupWindow = new GoodsPropPopView(mContext, goodsInfo);
				//				popupWindow = new GoodsPropPopView(mContext, goodsInfo);
				if (goodsInfo != null)
				{
					popupWindow = new GoodsPropPopView(mContext, goodsInfo, freeMoney, activityId);
					popupWindow.setSkuListener(new BuyNowListener());
					popupWindow.showWindow();
				}
				else
				{
					if (!(loadState == loadfail))
					{
						loadingDialog.show();
					}
				}
				break;
			case R.id.goods_main_bottom_shoppingcart_img:
				Intent intentCart = new Intent(this, ShoppingCartActivity.class);
				startActivity(intentCart);
				break;
			case R.id.goods_main_base_tab:
				setSelect(TAB_BASE);
				break;
			case R.id.goods_main_detail_tab:
				setSelect(TAB_DETAIL);
				break;
			
			default:
				break;
		}
		
	}
	
	private void setSelect(int a) {
		currentPage = a;
		tvGoodsBase.setSelected(a == TAB_BASE ? true : false);
		tvGoodsDetail.setSelected(a == TAB_DETAIL ? true : false);
		viewPager.setCurrentItem(a);
	}
	
	//	private void setViewAnimation() {
	//		ObjectAnimator oa=ObjectAnimator.ofFloat(getWindow().getAttributes(), "alpha", 0f, 1f);
	//		oa.setDuration(3000);
	//		oa.start();
	//    }
	
	void goback() {
		if (viewList.get(currentPage).webView.canGoBack())
		{
			viewList.get(currentPage).webView.goBack();
		}
		else
		{
			setResult(RESULT_OK);
			finish();
		}
	}
	
	@Override
	public void onBackPressed() {
		goback();
	}
	
	/**
	 * 加入购物车popView监听器
	 * 
	 * @author xuzhijun
	 * @date 2015年4月17日 下午12:40:13
	 */
	private class ShoppingCartAddListener
	        implements
	        GoodsPropViewListener
	{
		
		@Override
		public void OK(GoodsSkuMapInfo goodsSkuMapInfo, String propString, int count, Dialog d, long activityId, int freeMoney) {
			shoppingCartDao = ShoppingCartDao.getInstance(mContext);
			ShoppingCart goods;
			if (goodsSkuMapInfo != null)
			{
				goods = new ShoppingCart(ActionHelp.getAccount(), goodsInfo.getGoodsId(), Integer.parseInt(AppConfig.getEnterpriseId()), goodsInfo.getTitle(), goodsInfo.getSellPoint(), goodsInfo.getShortDesc(), goodsInfo.getCoverUrl(), count, goodsSkuMapInfo.getPrice() - goodsInfo.getActivityPrice(), "n", goodsSkuMapInfo.getSkuId(), propString, System.currentTimeMillis());
			}
			else
			{
				goods = new ShoppingCart(ActionHelp.getAccount(), goodsInfo.getGoodsId(), Integer.parseInt(AppConfig.getEnterpriseId()), goodsInfo.getTitle(), goodsInfo.getSellPoint(), goodsInfo.getShortDesc(), goodsInfo.getCoverUrl(), count, goodsInfo.getSalePrice(), "n", 0, "", System.currentTimeMillis());
			}
			goods.activityId = activityId;
			goods.freeMoney = freeMoney;
			goods.goodsDetailUrl = goodsInfo.getDetailUrl();
			goods.baseUrl = goodsInfo.getBaseUrl();
			goods.goodsType = goodsInfo.getGoodsType();
			if (shoppingCartDao.add(goods) != -1)
			{
				Utils.ToastShow(mContext, "添加成功");
				d.dismiss();
			}
			else
			{
				Utils.ToastShow(mContext, "添加失败");
			}
		}
		
	}
	
	/**
	 * 立即购买popView监听器
	 * 
	 * @author xuzhijun
	 * @date 2015年4月17日 下午12:40:37
	 */
	private class BuyNowListener
	        implements
	        GoodsPropViewListener
	{
		
		@Override
		public void OK(GoodsSkuMapInfo goodsSkuMapInfo, String propString, int count, Dialog d, long activityId, int freeMoney) {
			shoppingCartDao = ShoppingCartDao.getInstance(NewGoodsMainActivity.this);
			ShoppingCart goods;
			if (goodsSkuMapInfo != null)
			{
				goods = new ShoppingCart(ActionHelp.getAccount(), goodsInfo.getGoodsId(), Integer.parseInt(AppConfig.getEnterpriseId()), goodsInfo.getTitle(), goodsInfo.getSellPoint(), goodsInfo.getShortDesc(), goodsInfo.getCoverUrl(), count, goodsSkuMapInfo.getPrice() - goodsInfo.getActivityPrice(), "n", goodsSkuMapInfo.getSkuId(), propString, System.currentTimeMillis());
			}
			else
			{
				goods = new ShoppingCart(ActionHelp.getAccount(), goodsInfo.getGoodsId(), Integer.parseInt(AppConfig.getEnterpriseId()), goodsInfo.getTitle(), goodsInfo.getSellPoint(), goodsInfo.getShortDesc(), goodsInfo.getCoverUrl(), count, goodsInfo.getSalePrice(), "n", 0, "", System.currentTimeMillis());
			}
			goods.goodsDetailUrl = goodsInfo.getDetailUrl();
			goods.activityId = activityId;
			goods.freeMoney = freeMoney;
			goods.baseUrl = goodsInfo.getBaseUrl();
			goods.goodsType = goodsInfo.getGoodsType();
			Intent confirmOrderIntent = new Intent(NewGoodsMainActivity.this, ConfirmOrderActivity.class);
			confirmOrderIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.CONFIRM_ORDER_FROM_GOODS_MAIN);
			confirmOrderIntent.putExtra(DefaultConsts.CONFIRM_ORDER_GOODS, goods);
			//			confirmOrderIntent.putExtra(DefaultConsts.GOODS_ACTIVITY_PRICE_ID, activityId);
			//			confirmOrderIntent.putExtra(DefaultConsts.GOODS_FREE_MONEY_TO_WAP, freeMoney);			
			
			startActivity(confirmOrderIntent);
			d.dismiss();
		}
		
	}
	
	private class ViewPagerWebAdapter
	        extends
	        PagerAdapter
	{
		
		@Override
		public int getCount() {
			return 2;
		}
		
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			
			return arg0 == arg1;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(viewList.get(position));
			
			return viewList.get(position);
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(viewList.get(position));
		}
	}
	
}
